package com.qf.common.core.utils;

import com.qf.data.entity.auth.base.BaseUser;
import com.qf.data.entity.auth.vo.SysUserVo;
import com.qf.data.entity.auth.vo.WxUserVo;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class BaseUserUtils {

    /**
     * 根据json字符串，创建对应的UserDetails对象
     * @param json
     * @return
     */
    public static BaseUser createUser(String json, Integer type){
        switch (type) {
            case 1:
                return JsonUtils.json2Obj(json, SysUserVo.class);
            case 2:
                return JsonUtils.json2Obj(json, WxUserVo.class);
        }
        return null;
    }

    /**
     * 根据参数Map创建对应的UserDetails对象（SysUserVo、WxUserVo）
     */
    public static BaseUser createUser(Map<String, ?> params){
        //判断用户的来源 1-系统用户 2-微信用户
        Integer fromType = (Integer) params.get("fromType");
        switch (fromType) {
            case 1: {
                //系统用户
                Integer uid = (Integer) params.get("uid");
                String nickname = (String) params.get("nickname");
                String username = (String) params.get("username");
                List<String> authoritys = (List<String>) params.get("authorities");
                List<GrantedAuthority> authorities = authoritys.stream()
                        .map(authStr -> new SimpleGrantedAuthority(authStr))
                        .collect(Collectors.toList());
                SysUserVo sysUserVo = new SysUserVo();
                sysUserVo.setUId(uid.longValue());
                sysUserVo.setUsername(username);
                sysUserVo.setNickName(nickname);
                sysUserVo.setAuthorities(authorities);
                return sysUserVo;
            }
            case 2: {
                //微信用户
                Integer wuid = (Integer) params.get("wuid");
                String nickname = (String) params.get("nickname");
                String username = (String) params.get("username");
                String headerImg = (String) params.get("headerImg");

                WxUserVo wxUserVo = new WxUserVo();
                wxUserVo.setWuId(wuid.longValue());
                wxUserVo.setUsername(username);
                wxUserVo.setNickName(nickname);
                wxUserVo.setHeaderImg(headerImg);
                return wxUserVo;
            }
        }
        return null;
    }
}
